<template>
  <div class="all">
    <el-container class="all_content">
      <Sidebar/>
      <el-container class="all_main">
        <el-header class="head">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item class="item"><span class="t">激活码列表</span></el-breadcrumb-item>
          </el-breadcrumb>
        </el-header>
        <el-main class="main">
          <div class="search-area">
            <div class="s">
              <el-input
                  v-model="searchForm.activationCode"
                  placeholder="输入激活码搜索"
                  clearable
                  style="width: 1000px; height:40px;"
                  @keyup.enter="fetchCodes"
              >
                <template #append>
                  <el-button @click="fetchCodes">  搜索  </el-button>
                </template>
              </el-input>
              <el-form-item>
                <el-select v-model="searchForm.createdBy"
                           placeholder="请选择身份"
                           style="width: 220px;padding-left: 10px"
                           @change="fetchCodes"
                >
                  <el-option label="&nbsp;&nbsp;&nbsp;&nbsp;教练" value="coach"/>
                  <el-option label="&nbsp;&nbsp;&nbsp;&nbsp;管理员" value="admin" />
                  <el-option label="&nbsp;&nbsp;&nbsp;&nbsp;全部" value="all" />
                </el-select>
              </el-form-item>
            </div>

          </div>
          <div class="table-wrapper" style="width: 100%;">
            <el-table
                :data="allcodes"
                border
                style="width: 90%;font-family: 'monospace';"
                :default-sort="{ prop: 'createTime', order: 'descending' }"
                @sort-change="handleSortChange"
                v-loading="loading"
                element-loading-text="数据加载中..."
            >
              <el-table-column type="index" label="序号" min-width="50" />
              <el-table-column prop="activatedBy[name]" label="姓名" min-width="120" />
              <el-table-column prop="activateCode" label="激活码" min-width="120" />
              <el-table-column prop="activatedBy[phone]" label="手机号" min-width="120" />
              <el-table-column label="创建时间" min-width="130">
                <template #default="scope">
                  {{ formatCreateTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="激活时间" min-width="130">
                <template #default="scope">
                  {{ formatCreateTime(scope.row.activatedTime) }}
                </template>
              </el-table-column>
              <el-table-column label="有效截止时间" min-width="130">
                <template #default="scope">
                  {{ formatCreateTime(scope.row.vipExpirationTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="used" label="使用状态" min-width="110">
                <template #default="scope">
                  {{ scope.row.used === true ? '使用中' : '未使用' }}
                </template>
              </el-table-column>
              <el-table-column prop="createdBy[name]" label="创建者" min-width="120" />
              <el-table-column prop="createdBy[type]" label="创建身份" min-width="100">
                <template #default="scope">
                  {{ scope.row.createdBy.type === 'coach' ? '教练' : '管理员' }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!--分页器-->
          <div class="pagination" style="padding: 20px 0 0 90px;">
            <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            />
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>


<script setup>
import Sidebar from '@/components/Sidebar.vue';
import { useRouter } from 'vue-router';
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import {getActivation} from "@/api/activation.js";
const router = useRouter();
const allcodes = ref([]);  //列表
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

const searchForm = ref({
  createdBy: 'all',
  page: 1,
  size: 10,
  sortBy: 'create_time', // 默认按创建时间排序
  sortOrder: 'desc',    // 默认降序
  activationCode:'',
  used:'true',
});

// 生命周期钩子：页面加载时获取数据
onMounted(() => {
  fetchCodes();
});

// 获取学员列表
const fetchCodes = async () => {
  loading.value = true;
  try {
    // 更新分页参数
    searchForm.value.page = currentPage.value;
    searchForm.value.size = pageSize.value;

    const response = await getActivation(
        {
          page: searchForm.value.page,
          size: searchForm.value.size,
          sortBy: searchForm.value.sortBy,
          sortOrder: searchForm.value.sortOrder,
          used:searchForm.value.used,
          activationCode:searchForm.value.activationCode,
          createdBy:searchForm.value.createdBy,
        }
    );
    if (response.status === 1 && response.content === "success")
    {
      allcodes.value = response.data.codes|| [];
      total.value = response.data.total || 0;
    }
    else
    {
      ElMessage.error('获取学员列表失败');
    }
  }
  catch (error)
  {
    ElMessage.error('网络错误，请重试');
    router.push('/login');
  }
  finally
  {
    loading.value = false;
  }
};

const handleSortChange = ({ prop, order }) => {
  // 转换排序字段和顺序
  const sortMap = {
    'createTime': 'create_time',
    'name': 'name',
    'phone': 'phone'
  };

  const orderMap = {
    'ascending': 'asc',
    'descending': 'desc'
  };

  searchForm.value.sortBy = sortMap[prop] || 'create_time';
  searchForm.value.sortOrder = orderMap[order] || 'desc';

  fetchCodes();
};

const formatCreateTime = (timeStr) => {
  if (!timeStr) return '';
  return timeStr.split('T')[0];

};



// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 切换页大小后重置为第一页
  fetchCodes();
};

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchCodes();
};




</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body
{
  padding: 0;
  margin: 0;
  height: 100vh;
  width: 100vh;
}

.all{
  width: 100%;
  height: 100%;
}
.all_content{
  display: flex;
  height: 100vh;
  width: 100%;
}

.all_main{
  width: 100vh;
  padding: 0px;
  margin: 0px;
}

.head {
  width: 100%;
  height: 4vh;
  display: flex;
  align-items: center;
  border-bottom: solid 1px rgba(204, 204, 204, 0.66);
}

.main{
  width: 100%;
}

.item {
  padding-left: 30px;
}

.t {
  color: #090909;
  font-size: 18px;
  font-weight: 500;
}
.s{
  display: flex;
}
.search-area {
  justify-content: center;
  gap: 10px;
  align-items: center;
  width: 1000px;
  margin: 20px auto;
}

.table-wrapper {
  display: flex;
  justify-content: center;
  overflow-x: auto;
}
.pagination {
  display: flex;
  justify-content: center;
  font-family:"Times New Roman" ;
}

</style>